﻿using HCQ2_Common;
using HCQ2_IBLL;
using HCQ2_Model;
using HCQ2_Model.VRDevice.ParamModel;
using HCQ2_Model.VRDevice.ResultModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HCQ2_BLL
{
    public partial class T_DocEmpowerBLL: IT_DocEmpowerBLL
    {
        /// <summary>
        ///  获取授权列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Task<List<AuthorUserResult>> GetAuthorUser(AuthorUser model)
        {
            return DBSession.IT_DocEmpowerDAL.GetAuthorUser(model);
        }
        /// <summary>
        ///  导入授权用户
        /// </summary>
        /// <param name="tempPath"></param>
        /// <returns></returns>
        public List<string> importUser(string tempPath, T_User u, out bool importMark)
        {
            importMark = false;
            //获取导入文件里面的数据
            Stopwatch sw = new Stopwatch();
            sw.Start();
            List<string> valid = new List<string>();
            DataTable excelData = NpoiHelper.ExcelToDataTable(tempPath, true, 0);
            if (excelData == null || excelData.Rows.Count<=0)
                valid.Add("无法获取到excel文件中数据");
            sw.Stop();
            valid = checkRequired(excelData);
            if (valid.Count > 0)
                return valid;
            //封装List
            List<T_DocEmpower> list = toImportModelTable(excelData,u);
            sw.Restart();
            list.ForEach(s => DBSession.IT_DocEmpowerDAL.Add(s));
            sw.Stop();
            importMark = true;
            return valid;
        }
        /// <summary>
        /// 验证必填信息是否为空
        /// </summary>
        /// <param name="excelData"></param>
        /// <returns></returns>
        private List<string> checkRequired(DataTable excelData)
        {
            List<string> valid = new List<string>();
            for (int i = 0; i < excelData.Rows.Count; i++)
            {
                //1.0 判断必填项是否为空
                int rowNum = (i + 1 + 1);
                if (excelData.Rows[i]["F1"] == null || string.IsNullOrEmpty(Convert.ToString(excelData.Rows[i]["F1"])))
                    valid.Add($"第{rowNum}行，用户登录名不允许为空！");
                else if (excelData.Rows[i]["F2"] == null || string.IsNullOrEmpty(Convert.ToString(excelData.Rows[i]["F2"])))
                    valid.Add($"第{rowNum}行，编号不允许为空！");
                else if (excelData.Rows[i]["F3"] == null || string.IsNullOrEmpty(Convert.ToString(excelData.Rows[i]["F3"])))
                    valid.Add($"第{rowNum}行，开始时间不允许为空！");
                else if (excelData.Rows[i]["F4"] == null || string.IsNullOrEmpty(Convert.ToString(excelData.Rows[i]["F4"])))
                    valid.Add($"第{rowNum}行，结束时间不允许为空！");
                //2.0 结束时间不能小于开始时间
                string ds = Convert.ToString(excelData.Rows[i]["F3"]), de = Convert.ToString(excelData.Rows[i]["F4"]);
                DateTime start, end;
                try
                {
                    start = DateTime.ParseExact(ds, "yyyy-MM-dd", new System.Globalization.CultureInfo("zh-CN"));//开始时间
                    end = DateTime.ParseExact(de, "yyyy-MM-dd", new System.Globalization.CultureInfo("zh-CN"));//截止时间
                }
                catch (Exception e) { throw new Exception("日期格式错误：yyyy-mm-dd"); }
                if(end< start)
                    valid.Add($"第{rowNum}行，结束时间：【{de}不能小于{ds}】开始时间！");
                //2.1 相同的登录名和编号，时间不能有交叉
                string loginName = Convert.ToString(excelData.Rows[i]["F1"]),//登录名
                    numCode = Convert.ToString(excelData.Rows[i]["F2"]);//编号
                var user = DBSession.IT_UserDAL.FindSingle(s => s.login_name.Equals(loginName));
                //2.3 判断是否存在：登录名
                if (user==null)
                    valid.Add($"第{rowNum}行，登录名：【{loginName}】在系统中不已存在！");
                else
                {
                    //2.2 登录名已被禁用
                    int limtCount = DBSession.IT_LimitUserDAL.SelectCount(s => s.user_id == user.user_id);
                    if (limtCount > 0)
                        valid.Add($"第{rowNum}行，登录名：【{loginName}】已被禁用！");
                    //登录名和编号是否存在
                    int mark = DBSession.IT_DocEmpowerDAL.SelectCount(s => s.user_id == user.user_id && s.num_code.Equals(numCode));
                    if(mark>0)
                        valid.Add($"第{rowNum}行，登录名：【{loginName}】编号：【{numCode}】在授权表中已存在！");
                }
            }
            return valid;
        }
        /// <summary>
        ///  数据转换为导入的数据
        /// </summary>
        /// <param name="excelData">原始数据</param>
        /// <param name="file_id"></param>
        /// <param name="file_name"></param>
        /// <param name="cp_id"></param>
        /// <param name="cp_name"></param>
        /// <returns></returns>
        private List<T_DocEmpower> toImportModelTable(DataTable excelData,T_User u)
        {
            List<T_DocEmpower> list = new List<T_DocEmpower>();
            for (int i = 0; i < excelData.Rows.Count; i++)
            {
                string ds = Convert.ToString(excelData.Rows[i]["F3"]),
                    de = Convert.ToString(excelData.Rows[i]["F4"]),
                    loginName = Convert.ToString(excelData.Rows[i]["F1"]);//登录名
                DateTime start = DateTime.ParseExact(ds, "yyyy-MM-dd", new System.Globalization.CultureInfo("zh-CN")),//开始时间
                    end = DateTime.ParseExact(de, "yyyy-MM-dd", new System.Globalization.CultureInfo("zh-CN"));//截止时间
                var user = DBSession.IT_UserDAL.FindSingle(s => s.login_name.Equals(loginName));
                list.Add(new T_DocEmpower
                {
                    num_code = Convert.ToString(excelData.Rows[i]["F2"]),
                    user_id = user.user_id,
                    limit_code = "VRPPT_ACCESS",
                    status = 1,
                    start_date = start,
                    end_date = end,
                    machine_code = Convert.ToString(excelData.Rows[i]["F5"]),
                    machine_name = Convert.ToString(excelData.Rows[i]["F6"]),
                    reg_id = u.user_id,
                    reg_name = u.user_name,
                    update_id = u.user_id,
                    update_name = u.user_name,
                    doc_note = Convert.ToString(excelData.Rows[i]["F7"])
                });
            }
            return list;
        }
    }
}